package com.wave.blefactory.ui

import android.Manifest
import android.annotation.SuppressLint
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.bluetooth.BluetoothAddress
import androidx.bluetooth.BluetoothDevice
import androidx.bluetooth.BluetoothLe
import androidx.bluetooth.ScanFilter
import androidx.core.app.ActivityCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import com.wave.blefactory.R
import com.wave.blefactory.databinding.FragmentHomeBinding
import com.wavefull.core.PermissionX
import com.wavefull.core.ext.nav
import com.wavefull.core.util.TaskManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.UUID

/**
 * https://juejin.cn/post/7354389281584119823#heading-3
 *     public static final String SERVICE_UUID = "6E400001-B5A3-F393-E0A9-E50E24DCCA9E";
 *     public static final String WRITE_UUID = "6E400002-B5A3-F393-E0A9-E50E24DCCA9E";
 *     public static final String NOTIFY_UUID = "6E400003-B5A3-F393-E0A9-E50E24DCCA9E";
 *     public static final String READ_POWER_UUID = "6E400004-B5A3-F393-E0A9-E50E24DCCA9E";
 *     public static final String READ_VERSION_UUID = "6E400006-B5A3-F393-E0A9-E50E24DCCA9E";
 *     public static final String DYNAMIC_UUID = "6E400007-B5A3-F393-E0A9-E50E24DCCA9E";
 */
class HomeFragment : Fragment() {
    private lateinit var binding: FragmentHomeBinding
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentHomeBinding.inflate(inflater, container, false)
        initView()
        initData()
        return binding.root
    }

    private fun initView() {
        binding.titleBar.setTitleText("主页").setLeftImg(false)
    }

    private fun initData() {
        binding.textHome.setOnClickListener {
            nav().navigate(R.id.action_homeFragment_to_secondFragment)
        }
        var permissions = arrayOf(
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA,
            Manifest.permission.VIBRATE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.BLUETOOTH,
            Manifest.permission.BLUETOOTH_ADMIN,

            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION
        )
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            permissions += Manifest.permission.BLUETOOTH_CONNECT
            permissions += Manifest.permission.BLUETOOTH_SCAN
        }
        PermissionX.with(this).permission(permissions).request {
            startBlueScan()
        }
    }

    @SuppressLint("MissingPermission")
    private fun startBlueScan() {
        val bluetoothLe = BluetoothLe(requireContext())
        //        bluetoothLe.scan(listOf(ScanFilter(serviceDataUuid = UUIDS.UUID_FOR_FILTER, deviceName = "XXXX")))
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && ActivityCompat.checkSelfPermission(
                requireContext(),
                Manifest.permission.BLUETOOTH_SCAN
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            Log.d(TAG, "initData: 没权限")
            return
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && ActivityCompat.checkSelfPermission(
                requireContext(),
                Manifest.permission.BLUETOOTH_CONNECT
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            Log.d(TAG, "initData: 没权限")
            return
        }
        val scanResultFlow = bluetoothLe.scan()
        val job = lifecycleScope.launch {
            scanResultFlow.collect {
                Log.d(
                    TAG,
                    "initData: ${it.device.name}, ${it.deviceAddress.address},${it.deviceAddress.addressType}"
                )
                val device = it.device
                if (device.name == "") {
                    TaskManager.stopTask("jobC")
                    bluetoothLe.connectGatt(device) {
                        val gattService = getService(UUID.fromString("GATT_BATTERY_SERVICE_UUID"))
                        val batteryLevel =
                            gattService?.getCharacteristic(UUID.fromString("GATT_BATTERY_LEVEL_UUID"))
                                ?: return@connectGatt
                        val result = readCharacteristic(batteryLevel)
                        if (result.isSuccess) {
                            val value = result.getOrNull() ?: return@connectGatt
                            val battery = value[0].toInt() and 0xff
                            Log.i(TAG, "battery:$battery")
                        }
                    }
                }
            }
        }
        TaskManager.startTask("jobC", 5000) {
            job.cancel()
        }
    }

    companion object {
        private const val TAG = "HomeFragment"
    }
}